/*
 * Copyright (c) 2008-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.html;

import java.awt.Color;

import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.EditorKit;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.html.HTML;

import org.panteleyev.html.syntax.Highlighter;
import org.panteleyev.utilities.ColorConverter;

public class PlainEditor extends Editor {
    private StyledEditorKit kit;
    private DefaultStyledDocument doc;
    private Highlighter highlighter;

    public PlainEditor() {
        kit = new StyledEditorKit();
    }

    @Override
    public EditorKit getKit() {
        return kit;
    }

    @Override
    public DefaultStyledDocument getDocument() {
        return doc;
    }

    @Override
    public String getHtml() {
        return (getEditorPane() == null)? null : getEditorPane().getText();
    }

    @Override
    public void newDocument() {
        doc = new DefaultStyledDocument();
        getEditorPane().setDocument(doc);

        highlighter = new Highlighter(getEditorPane());

        getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                SwingUtilities.invokeLater(highlighter);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                SwingUtilities.invokeLater(highlighter);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });
    }

    @Override
    public void insertHTML(String html, HTML.Tag startTag) {
        getEditorPane().replaceSelection(html);
        getEditorPane().requestFocus();
    }

    @Override
    public void setBold() {
        onFormatTag("b");
    }

    @Override
    public void setItalic() {
        onFormatTag("i");
    }

    @Override
    public void setUnderline() {
        onFormatTag("u");
    }

    @Override
    public void setStrikeThrough() {
        onFormatTag("strike");
    }

    private void onFormatTag(String tag) {
        String sel = getEditorPane().getSelectedText();
        StringBuilder b = new StringBuilder("<");
        b.append(tag);
        b.append(">");

        if (sel != null) {
            b.append(sel);
        }
        b.append("</");
        b.append(tag);
        b.append(">");
        insertText(b.toString());
    }

    private void onFormatTag(String open, String close) {
        String sel = getEditorPane().getSelectedText();
        StringBuilder b = new StringBuilder(open);
        if (sel != null) {
            b.append(sel);
        }
        b.append(close);
        insertText(b.toString());
    }

    @Override
    public void onInsertLink(HTMLLinkDialog dial) {
        dial.setInnerHTML(getEditorPane().getSelectedText());

        if (dial.showDialog()) {
            insertText(dial.getReference());
        }
    }

    @Override
    public void onInsertImage(HTMLImageDialog dial) {
        dial.setAltText(getEditorPane().getSelectedText());

        if (dial.showDialog()) {
            insertText(dial.getReference());
        }
    }

    @Override
    public void setForegroundColor(Color color) {
        String htmlColor = ColorConverter.RGBtoHTML(color.getRGB());
        onFormatTag("<font color='" + htmlColor + "'>", "</font>");
    }

    @Override
    public void encloseText(char open, char close) {
        String sel = getEditorPane().getSelectedText();

        StringBuilder b = new StringBuilder("&#");
        b.append(Integer.toString(open));
        b.append(";");

        if (sel != null) {
            b.append(sel);
        }

        b.append("&#");
        b.append(Integer.toString(close));
        b.append(";");

        insertText(b.toString());
    }

    @Override
    public void insertUnicodeCharacter(char c) {
        StringBuilder b = new StringBuilder("&#");
        b.append(Integer.toString(c));
        b.append(";");
        getEditorPane().replaceSelection(b.toString());
        getEditorPane().requestFocus();
    }

    @Override
    public void setFormatTag(HTML.Tag tag) {
        String sel = getEditorPane().getSelectedText();
        StringBuilder b = new StringBuilder("<");
        b.append(tag);
        b.append(">");

        if (sel != null) {
            b.append(sel);
        }
        b.append("</");
        b.append(tag);
        b.append(">");
        insertText(b.toString());
    }

    @Override
    public String getTextForPost() {
        return getHtml();
    }

    @Override
    public String getTextForPreview(boolean convertLineBreaks) {
        String text = getHtml();
        if (text != null) {
            if (convertLineBreaks) {
                text = text.replaceAll("\n", "<br>");
            }
        }

        return text;
    }

    @Override
    public void fontUpdated() {
        super.fontUpdated();
        highlighter.fontUpdated();
    }

}
